<template>
    <div class="register-page">
        <!-- 背景装饰 -->
        <div class="bg-decoration">
            <div class="bg-circle bg-circle-1"></div>
            <div class="bg-circle bg-circle-2"></div>
            <div class="bg-circle bg-circle-3"></div>
        </div>
        
        <div class="register-container">
            <!-- 左侧欢迎区域 -->
            <div class="welcome-section">
                <div class="welcome-content">
                    <div class="medical-icon">
                        <svg viewBox="0 0 24 24" fill="currentColor">
                            <path d="M12 2C13.1 2 14 2.9 14 4V6H16C17.1 6 18 6.9 18 8V10C19.1 10 20 10.9 20 12S19.1 14 18 14V16C18 17.1 17.1 18 16 18H14V20C14 21.1 13.1 22 12 22S10 21.1 10 20V18H8C6.9 18 6 17.1 6 16V14C4.9 14 4 13.1 4 12S4.9 10 6 10V8C6 6.9 6.9 6 8 6H10V4C10 2.9 10.9 2 12 2Z"/>
                        </svg>
                    </div>
                    <h1 class="welcome-title">
                        <span class="gradient-text">加入我们</span>
                    </h1>
                    <p class="welcome-subtitle">
                        注册京东医疗账户，享受专业医疗服务
                    </p>
                    <div class="feature-list">
                        <div class="feature-item">
                            <div class="feature-icon">👨‍⚕️</div>
                            <span>专业医师</span>
                        </div>
                        <div class="feature-item">
                            <div class="feature-icon">🏥</div>
                            <span>权威医院</span>
                        </div>
                        <div class="feature-item">
                            <div class="feature-icon">💊</div>
                            <span>便民药房</span>
                        </div>
                        <div class="feature-item">
                            <div class="feature-icon">🔒</div>
                            <span>信息安全</span>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 右侧注册表单 -->
            <div class="register-card">
                <div class="brand">
                    <div class="register-type-tabs">
                        <div 
                            class="tab-item" 
                            :class="{ active: registerType === 'user' }"
                            @click="registerType = 'user'"
                        >
                            <div class="tab-icon">👤</div>
                            <span>普通用户</span>
                        </div>
                        <div 
                            class="tab-item" 
                            :class="{ active: registerType === 'doctor' }"
                            @click="registerType = 'doctor'"
                        >
                            <div class="tab-icon">👨‍⚕️</div>
                            <span>医生注册</span>
                        </div>
                    </div>
                    <h2>{{ registerType === 'user' ? '用户注册' : '医生注册' }}</h2>
                    <p class="subtitle">{{ registerType === 'user' ? '创建您的京东医疗账户' : '加入京东医疗医师团队' }}</p>
                </div>

                <el-form
                    ref="formRef"
                    :model="form"
                    :rules="rules"
                    label-position="top"
                    class="register-form"
                    @keyup.enter.native="onSubmit"
                >
                    <!-- 通用字段 -->
                    <el-form-item label="用户名" prop="username" class="form-item">
                        <el-input
                            v-model.trim="form.username"
                            placeholder="请输入用户名（2-32个字符）"
                            clearable
                            :prefix-icon="User"
                            autofocus
                            size="large"
                        />
                    </el-form-item>

                    <!-- 医生注册专用字段 -->
                    <template v-if="registerType === 'doctor'">
                        <el-form-item label="真实姓名" prop="realName" class="form-item">
                            <el-input
                                v-model.trim="form.realName"
                                placeholder="请输入您的真实姓名"
                                clearable
                                :prefix-icon="UserFilled"
                                size="large"
                            />
                        </el-form-item>

                        <el-form-item label="所属医院" prop="hospitalName" class="form-item">
                            <el-input
                                v-model.trim="form.hospitalName"
                                placeholder="请输入您所在的医院名称"
                                clearable
                                size="large"
                            />
                        </el-form-item>

                        <el-form-item label="科室" prop="department" class="form-item">
                            <el-select
                                v-model="form.department"
                                placeholder="请选择您的科室"
                                size="large"
                                style="width: 100%"
                                clearable
                            >
                                <el-option label="内科" value="内科" />
                                <el-option label="外科" value="外科" />
                                <el-option label="妇产科" value="妇产科" />
                                <el-option label="儿科" value="儿科" />
                                <el-option label="骨科" value="骨科" />
                                <el-option label="心内科" value="心内科" />
                                <el-option label="神经内科" value="神经内科" />
                                <el-option label="皮肤科" value="皮肤科" />
                                <el-option label="眼科" value="眼科" />
                                <el-option label="耳鼻喉科" value="耳鼻喉科" />
                                <el-option label="口腔科" value="口腔科" />
                                <el-option label="中医科" value="中医科" />
                                <el-option label="其他" value="其他" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="职称" prop="title" class="form-item">
                            <el-select
                                v-model="form.title"
                                placeholder="请选择您的职称"
                                size="large"
                                style="width: 100%"
                                clearable
                            >
                                <el-option label="住院医师" value="住院医师" />
                                <el-option label="主治医师" value="主治医师" />
                                <el-option label="副主任医师" value="副主任医师" />
                                <el-option label="主任医师" value="主任医师" />
                                <el-option label="实习医师" value="实习医师" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="执业医师证号" prop="licenseNumber" class="form-item">
                            <el-input
                                v-model.trim="form.licenseNumber"
                                placeholder="请输入执业医师证号"
                                clearable
                                size="large"
                            />
                        </el-form-item>

                        <el-form-item label="从业经验" prop="experience" class="form-item">
                            <el-input
                                v-model.trim="form.experience"
                                type="textarea"
                                :rows="3"
                                placeholder="请简述您的从业经验和专业特长"
                                size="large"
                            />
                        </el-form-item>
                    </template>

                    <!-- 普通用户注册字段 -->
                    <template v-else>
                        <el-form-item label="昵称" prop="nickname" class="form-item">
                            <el-input
                                v-model.trim="form.nickname"
                                placeholder="请输入昵称（可选，默认为用户名）"
                                clearable
                                :prefix-icon="UserFilled"
                                size="large"
                            />
                        </el-form-item>
                    </template>

                    <!-- 通用联系方式字段 -->
                    <el-form-item label="邮箱" prop="email" class="form-item">
                        <el-input
                            v-model.trim="form.email"
                            :placeholder="registerType === 'doctor' ? '请输入邮箱地址（必填）' : '请输入邮箱地址（可选）'"
                            clearable
                            :prefix-icon="Message"
                            size="large"
                        />
                    </el-form-item>

                    <el-form-item label="手机号" prop="phone" class="form-item">
                        <el-input
                            v-model.trim="form.phone"
                            :placeholder="registerType === 'doctor' ? '请输入手机号（必填）' : '请输入手机号（可选）'"
                            clearable
                            :prefix-icon="Phone"
                            size="large"
                        />
                    </el-form-item>

                    <el-form-item label="密码" prop="password" class="form-item">
                        <el-input
                            v-model="form.password"
                            placeholder="请输入密码（6-64个字符）"
                            show-password
                            type="password"
                            :prefix-icon="Lock"
                            size="large"
                        />
                    </el-form-item>

                    <el-form-item label="确认密码" prop="confirmPassword" class="form-item">
                        <el-input
                            v-model="form.confirmPassword"
                            placeholder="请再次输入密码"
                            show-password
                            type="password"
                            :prefix-icon="Lock"
                            size="large"
                        />
                    </el-form-item>

                    <!-- 医生注册提示 -->
                    <div v-if="registerType === 'doctor'" class="doctor-notice">
                        <div class="notice-icon">ℹ️</div>
                        <div class="notice-text">
                            <p><strong>医生注册须知：</strong></p>
                            <p>• 请确保填写真实、准确的个人信息</p>
                            <p>• 注册后需要平台审核，审核通过后方可提供医疗服务</p>
                            <p>• 如有疑问，请联系客服：400-123-4567</p>
                        </div>
                    </div>

                    <el-button
                        type="primary"
                        size="large"
                        class="submit-btn"
                        :loading="submitting"
                        @click="onSubmit"
                        block
                    >
                        <span v-if="!submitting">
                            {{ registerType === 'doctor' ? '提交医生注册申请' : '立即注册' }}
                        </span>
                        <span v-else>
                            {{ registerType === 'doctor' ? '提交申请中...' : '注册中...' }}
                        </span>
                    </el-button>

                    <div class="helper-row">
                        <span class="helper-text">已有账号？</span>
                        <el-link type="primary" :underline="false" @click="goToLogin" class="login-link">
                            立即登录
                        </el-link>
                    </div>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Phone, UserFilled } from '@element-plus/icons-vue'
import request from '@/utils/request'

const router = useRouter()

const formRef = ref(null)
const submitting = ref(false)
const registerType = ref('user') // 'user' 或 'doctor'

const form = reactive({
    username: '',
    nickname: '',
    email: '',
    phone: '',
    password: '',
    confirmPassword: '',
    // 医生注册专用字段
    realName: '',
    hospitalName: '',
    department: '',
    title: '',
    licenseNumber: '',
    experience: '',
})

const validateConfirmPassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== form.password) {
        callback(new Error('两次输入的密码不一致'))
    } else {
        callback()
    }
}

const validateEmail = (rule, value, callback) => {
    if (!value) {
        callback()
        return
    }
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
    if (!emailRegex.test(value)) {
        callback(new Error('请输入正确的邮箱格式'))
    } else {
        callback()
    }
}

const validatePhone = (rule, value, callback) => {
    if (!value) {
        callback()
        return
    }
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(value)) {
        callback(new Error('请输入正确的手机号格式'))
    } else {
        callback()
    }
}

const rules = computed(() => {
    const baseRules = {
        username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 2, max: 32, message: '长度应为 2-32 个字符', trigger: 'blur' },
        ],
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 64, message: '长度应为 6-64 个字符', trigger: 'blur' },
        ],
        confirmPassword: [
            { required: true, validator: validateConfirmPassword, trigger: 'blur' },
        ],
    }
    
    if (registerType.value === 'doctor') {
        // 医生注册的验证规则
        return {
            ...baseRules,
            realName: [
                { required: true, message: '请输入真实姓名', trigger: 'blur' },
                { min: 2, max: 20, message: '长度应为 2-20 个字符', trigger: 'blur' },
            ],
            hospitalName: [
                { required: true, message: '请输入所属医院', trigger: 'blur' },
            ],
            department: [
                { required: true, message: '请选择科室', trigger: 'change' },
            ],
            title: [
                { required: true, message: '请选择职称', trigger: 'change' },
            ],
            licenseNumber: [
                { required: true, message: '请输入执业医师证号', trigger: 'blur' },
            ],
            email: [
                { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                { validator: validateEmail, trigger: 'blur' },
            ],
            phone: [
                { required: true, message: '请输入手机号', trigger: 'blur' },
                { validator: validatePhone, trigger: 'blur' },
            ],
        }
    } else {
        // 普通用户注册的验证规则
        return {
            ...baseRules,
            email: [
                { validator: validateEmail, trigger: 'blur' },
            ],
            phone: [
                { validator: validatePhone, trigger: 'blur' },
            ],
        }
    }
})

async function onSubmit() {
    if (!formRef.value) return
    try {
        await formRef.value.validate()
        submitting.value = true
        
        if (registerType.value === 'doctor') {
            // 医生注册（模拟提交，不调用真实接口）
            console.log('医生注册申请:', {
                type: 'doctor',
                username: form.username,
                realName: form.realName,
                hospitalName: form.hospitalName,
                department: form.department,
                title: form.title,
                licenseNumber: form.licenseNumber,
                email: form.email,
                phone: form.phone,
                experience: form.experience,
                password: '***'
            })
            
            // 模拟网络延迟
            await new Promise(resolve => setTimeout(resolve, 2000))
            
            ElMessage.success('医生注册申请提交成功！我们将在3-5个工作日内完成审核，请耐心等待。')
            
            // 跳转回登录页面
            router.push('/')
        } else {
            // 普通用户注册（调用真实接口）
            console.log('发送注册请求:', { 
                username: form.username, 
                nickname: form.nickname,
                email: form.email,
                phone: form.phone,
                password: '***' 
            })
            
            const response = await request.post('/user/register', {
                username: form.username,
                nickname: form.nickname || form.username,
                email: form.email,
                phone: form.phone,
                password: form.password,
                confirmPassword: form.confirmPassword,
            })
            
            console.log('收到响应:', response)
            const data = response.data
            console.log('响应数据:', data)
            
            if (data && data.code === 0) {
                const token = data.data?.token
                const user = data.data?.user
                
                if (!token) throw new Error('注册成功但未返回 token')
                
                // 保存token
                localStorage.setItem('token', token)
                
                ElMessage.success(data.msg || '注册成功！欢迎加入京东医疗！')
                
                // 跳转到首页
                router.push({ path: '/home' })
            } else {
                throw new Error(data?.msg || '注册失败')
            }
        }
    } catch (err) {
        console.error('注册错误详情:', err)
        console.error('错误响应:', err.response)
        if (err.response && err.response.data && err.response.data.msg) {
            ElMessage.error(err.response.data.msg)
        } else if (err.message) {
            ElMessage.error(err.message)
        } else {
            ElMessage.error(registerType.value === 'doctor' ? '申请提交失败，请稍后重试' : '注册失败，请稍后重试')
        }
    } finally {
        submitting.value = false
    }
}

function goToLogin() {
    router.push('/')
}
</script>

<style scoped>
/* 页面主体 */
.register-page {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    position: relative;
    overflow: hidden;
}

/* 背景装饰 */
.bg-decoration {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    pointer-events: none;
}

.bg-circle {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
    animation: float 6s ease-in-out infinite;
}

.bg-circle-1 {
    width: 200px;
    height: 200px;
    top: 10%;
    left: 10%;
    animation-delay: 0s;
}

.bg-circle-2 {
    width: 150px;
    height: 150px;
    top: 60%;
    right: 15%;
    animation-delay: 2s;
}

.bg-circle-3 {
    width: 100px;
    height: 100px;
    bottom: 20%;
    left: 60%;
    animation-delay: 4s;
}

@keyframes float {
    0%, 100% { transform: translateY(0px) rotate(0deg); }
    50% { transform: translateY(-20px) rotate(180deg); }
}

/* 主容器 */
.register-container {
    display: flex;
    width: 1100px;
    max-width: 90vw;
    min-height: 700px;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    border-radius: 20px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
    overflow: hidden;
}

/* 欢迎区域 */
.welcome-section {
    flex: 1;
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 60px 40px;
    position: relative;
}

.welcome-section::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="medical" width="50" height="50" patternUnits="userSpaceOnUse"><path d="M25 15 L25 20 L20 20 L20 30 L25 30 L25 35 L30 35 L30 30 L35 30 L35 20 L30 20 L30 15 Z" fill="rgba(255,255,255,0.05)"/></pattern></defs><rect width="100" height="100" fill="url(%23medical)"/></svg>');
    opacity: 0.3;
}

.welcome-content {
    text-align: center;
    color: white;
    z-index: 1;
    position: relative;
}

.medical-icon {
    width: 80px;
    height: 80px;
    margin: 0 auto 20px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(10px);
    animation: pulse 2s ease-in-out infinite;
}

.medical-icon svg {
    width: 40px;
    height: 40px;
    color: white;
}

.welcome-title {
    font-size: 2.5rem;
    margin-bottom: 1rem;
    font-weight: 700;
}

.gradient-text {
    background: linear-gradient(45deg, #fff, #e6f7ff);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.welcome-subtitle {
    font-size: 1.1rem;
    margin-bottom: 2rem;
    opacity: 0.9;
    line-height: 1.6;
}

.feature-list {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.feature-item {
    display: flex;
    align-items: center;
    gap: 1rem;
    font-size: 1rem;
    opacity: 0.9;
}

.feature-icon {
    font-size: 1.5rem;
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    backdrop-filter: blur(10px);
}

@keyframes pulse {
    0%, 100% { transform: scale(1); opacity: 0.3; }
    50% { transform: scale(1.1); opacity: 0.6; }
}

/* 注册卡片 */
.register-card {
    flex: 1;
    padding: 40px 50px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    max-height: 700px;
    overflow-y: auto;
}

/* 品牌区域 */
.brand {
    text-align: center;
    margin-bottom: 30px;
}

/* 注册类型切换标签 */
.register-type-tabs {
    display: flex;
    background: #f8f9fa;
    border-radius: 12px;
    padding: 4px;
    margin-bottom: 20px;
    gap: 4px;
}

.tab-item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 12px 16px;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    color: #6c757d;
    font-weight: 500;
    font-size: 0.9rem;
}

.tab-item:hover {
    background: rgba(79, 172, 254, 0.1);
    color: #4facfe;
}

.tab-item.active {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    color: white;
    box-shadow: 0 2px 8px rgba(79, 172, 254, 0.3);
}

.tab-icon {
    font-size: 1.2rem;
}



.brand h2 {
    margin: 0 0 6px 0;
    font-weight: 700;
    font-size: 1.6rem;
    color: #1890ff;
}

.brand .subtitle {
    margin: 0;
    color: #6c757d;
    font-size: 0.9rem;
}

/* 表单样式 */
.register-form {
    margin-top: 0;
}

.form-item {
    margin-bottom: 18px;
}

.form-item :deep(.el-form-item__label) {
    color: #4a5568;
    font-weight: 600;
    margin-bottom: 6px;
    font-size: 0.9rem;
}

.form-item :deep(.el-input__wrapper) {
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border: 1px solid #e2e8f0;
    transition: all 0.3s ease;
}

.form-item :deep(.el-input__wrapper:hover) {
    border-color: #4facfe;
    box-shadow: 0 4px 12px rgba(79, 172, 254, 0.15);
}

.form-item :deep(.el-input__wrapper.is-focus) {
    border-color: #4facfe;
    box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
}

/* 医生注册提示 */
.doctor-notice {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
    border: 1px solid #91d5ff;
    border-radius: 10px;
    padding: 16px;
    margin-bottom: 20px;
}

.notice-icon {
    font-size: 1.2rem;
    margin-top: 2px;
}

.notice-text {
    flex: 1;
    font-size: 0.85rem;
    color: #1890ff;
    line-height: 1.5;
}

.notice-text p {
    margin: 0 0 4px 0;
}

.notice-text p:last-child {
    margin-bottom: 0;
}

/* 提交按钮 */
.submit-btn {
    height: 44px;
    border-radius: 10px;
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    border: none;
    font-weight: 600;
    font-size: 1rem;
    margin: 20px 0 25px 0;
    transition: all 0.3s ease;
}

.submit-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(79, 172, 254, 0.4);
}

.submit-btn:active {
    transform: translateY(0);
}

/* 帮助行 */
.helper-row {
    text-align: center;
    color: #6c757d;
    font-size: 0.9rem;
}

.helper-text {
    margin-right: 8px;
}

.login-link {
    font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .register-container {
        flex-direction: column;
        width: 95vw;
        min-height: auto;
    }
    
    .welcome-section {
        padding: 30px 20px;
        min-height: 200px;
    }
    
    .welcome-title {
        font-size: 2rem;
    }
    
    .feature-list {
        flex-direction: row;
        justify-content: center;
        flex-wrap: wrap;
    }
    
    .register-card {
        padding: 30px 25px;
        max-height: none;
    }
    
    .brand h2 {
        font-size: 1.4rem;
    }
}

@media (max-width: 480px) {
    .register-card {
        padding: 25px 20px;
    }
}
</style> 